package com.syt.cellphone.information.ui.main

import android.os.Bundle
import android.view.KeyEvent
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import androidx.viewpager.widget.ViewPager
import com.syt.cellphone.information.R
import com.syt.cellphone.information.base.VMBaseActivity
import com.syt.cellphone.information.lib.theme.ATH
import com.syt.cellphone.information.ui.main.brand.BrandFragment
import com.syt.cellphone.information.ui.main.phone.PhoneFragment
import com.syt.cellphone.information.ui.main.setting.SettingFragment
import com.syt.cellphone.information.ui.main.soc.SocFragment
import com.syt.cellphone.information.utils.getViewModel
import com.syt.cellphone.information.utils.hideSoftInput
import kotlinx.android.synthetic.main.activity_main.*
import org.jetbrains.anko.toast

/**
 *  @author: syt
 *  创建时间: 2020/8/24 14:37
 *  @功能   主活动
 *  @version v1.0
 */
class MainActivity : VMBaseActivity<MainViewModel>(R.layout.activity_main) {

    override val viewModel: MainViewModel
        get() = getViewModel(MainViewModel::class.java)

    private val fragmentId = arrayOf(0, 1, 2, 3)
    private val fragmentMap = mapOf<Int, Fragment>(
        Pair(fragmentId[0], PhoneFragment()),
        Pair(fragmentId[1], BrandFragment()),
        Pair(fragmentId[2], SocFragment()),
        Pair(fragmentId[3], SettingFragment())
    )
    // 当前的fragment
    private var pagePosition = 0
    // 点击底部按钮的时间
    private var phoneReselected: Long = 0

    private val tag = this.javaClass.name

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        ATH.applyEdgeEffectColor(view_pager_main)
        ATH.applyBottomNavigationColor(bottom_navigation_view_main)
        // 设置保存几页
        view_pager_main.offscreenPageLimit = 4
        // 设置视图适配器
        view_pager_main.adapter = TabFragmentPageAdapter(supportFragmentManager)
        // viewpager改变监听
        view_pager_main.addOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() {
            override fun onPageSelected(position: Int) {
                view_pager_main.hideSoftInput()
                pagePosition = position
                if (pagePosition > 1) {
                    pagePosition += 1
                }
                // 选中状态
                bottom_navigation_view_main.menu.getItem(pagePosition).isChecked = true
            }
        })
        // 底部选中监听器 -> 用于处理底部导航项上的重选事件 -> 再次选择底部导航菜单中的当前选定项目时调用
        bottom_navigation_view_main.setOnNavigationItemReselectedListener {
            when(it.itemId) {
                R.id.menu_main_phone -> {
                    // 间隔时长0.3秒
                    if (System.currentTimeMillis() - phoneReselected < 300) {
                        phoneReselected = System.currentTimeMillis()
                    } else {
                        // 刷新界面，来到界面顶部
                        (fragmentMap[0] as? PhoneFragment)?.gotoTop()
                        toast("置顶提示 刷新没做")
                    }
                }
            }
        }
        // 底部选中监听器,用于处理底部导航项上的选择事件。
        bottom_navigation_view_main.setOnNavigationItemSelectedListener {
            when(it.itemId) {
                R.id.menu_main_phone -> view_pager_main.setCurrentItem(0, false)
                R.id.menu_main_brand -> view_pager_main.setCurrentItem(1, false)
                R.id.menu_main_soc -> view_pager_main.setCurrentItem(2, false)
                R.id.menu_main_my_config -> view_pager_main.setCurrentItem(3, false)
                else -> {
                    toast("点击了其它地方")
                    try {
                        // 启动钉钉失败，打卡界面是个web
                        startActivity(packageManager.getLaunchIntentForPackage("com.alibaba.android.rimet"))
                    } catch (e: Exception) {
                        toast("没有找到应用")
                    }
                }
            }
            false
        }
    }

    // 上一次按返回键的时间
    private var exitTime = 0L

    override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
        event?.let {
            when(keyCode) {
                KeyEvent.KEYCODE_BACK -> if (event.isTracking && !event.isCanceled) {
                    if (pagePosition != 0) {
                        view_pager_main.currentItem = 0
                        return true
                    }
                    if (System.currentTimeMillis() - exitTime > 2000) {
                        toast(R.string.double_click_exit)
                        exitTime = System.currentTimeMillis()
                    } else {
                        moveTaskToBack(true)
                    }
                    return true
                }
            }
        }
        return super.onKeyUp(keyCode, event)
    }

    /**
     * fragment tab 的适配器
     */
    private inner class TabFragmentPageAdapter
    internal constructor(fm: FragmentManager) :
    FragmentStatePagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {

        override fun getItem(position: Int): Fragment {
            return when (position) {
                0 -> fragmentMap.getValue(fragmentId[0])
                1 -> fragmentMap.getValue(fragmentId[1])
                2 -> fragmentMap.getValue(fragmentId[2])
                3 -> fragmentMap.getValue(fragmentId[3])
                else -> fragmentMap.getValue(fragmentId[0])
            }
        }

        override fun getCount(): Int {
            return 4
        }

    }
}